<?php

namespace App;

use App\Helpers\Helpers;
use App\Model\UserAuthTag;
use App\Model\UserCoupon;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable  implements JWTSubject
{
    use Notifiable,SoftDeletes;

    protected $table = "t_user";

    protected $appends = ['user_roles'];
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['password_confirmation'];


    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','roles','session_key','weixinId'
    ];

    //获取表字段
    public function tableColumns()
    {
        return Schema::getColumnListing($this->getTable());
    }

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public function wechat()
    {
        return $this->hasOne('App\Model\UserWechat','user_id','id');
    }

    public function article()
    {
        return $this->hasMany('App\Model\Article','user_id','id');
    }

    public function roles()
    {
        return $this->belongsToMany('App\Model\Role','t_user_role','user_id','role_id','user_id');
    }

    public function getUserRolesAttribute()
    {
        return $this->roles;
    }
    public function parent()
    {
        return $this->belongsTo('App\User','parent_id','id');
    }

    public function getIsNewUserAttribute()
    {

    }

    //
    public function updateOrderCount()
    {
        self::updateOrderCountByUserId($this->id);
    }

    public static function updateOrderCountByUserId($user_id)
    {
        $c = DB::table('orders')->where('create_user_id','=',$user_id)
            ->whereNull('deleted_at')
            ->whereIn('state',[1,3,4,5,6])->count();

        return DB::table('t_user')->where('id','=',$user_id)->update([
            'order_count' => $c
        ]);
    }

    public static function findByWeixinId($weixinId)
    {
        return User::where('weixinId','=',$weixinId)->first();
    }

    public static function findByInviteCode($invite_code)
    {
        return User::where('invite_code','=',$invite_code)->first();
    }

    public function updateUserInfoFromWechat($wechat)
    {

        $sex = [0=>'未知',1=>'男',2=>'女'];

        if(!$this->name && isset($wechat['nickName']) && $wechat['nickName']){
            $this->name = $wechat['nickName'];
        }
        if(isset($wechat['gender']) && $wechat['gender'] && isset($sex[$wechat['gender']])){
            $this->sex = $sex[$wechat['gender']];
        }
        if(isset($wechat['avatarUrl']) && $wechat['avatarUrl']){
            $this->avatar = $wechat['avatarUrl'];
        }
        $this->save();

        return $wechat;
    }

    public function beforeSave()
    {
        if ($this->authTag&&!$this->chAuthTag){
            $this->chAuthTag = UserAuthTag::getNameByCode($this->authTag);
        }
        return true;
    }
    public function afterSave($input=null)
    {
        return true;
    }

    //用户登陆之后
    public function afterLogin()
    {
        return true;
    }

    //登录更新信息
    public function updateFromLogin($request,$newUser=false)
    {
        $parent = false;
        //绑定邀请人
        $invite_code = $request->input('invite_code',false);
        if(!$this->parent_id && $newUser && $invite_code){
            if($parent = self::findByInviteCode($invite_code)){
                $this->parent_id = $parent->id;
                $this->save();
            }

        }
        $parent = self::findByInviteCode($invite_code);
        if ($newUser && $parent) {
            $conf = DB::table('sys_seting_configs')->where('key','=','invite_user_coupon')->whereNull('deleted_at')->first();
            if ($conf){
                UserCoupon::getCoupons($parent->id,$conf->value,'invite_user_coupon');
            }
        }

        //用户基础信息
        if ($userInfo = $request->input('userInfo')) {
            try{
                $this->updateUserInfoFromWechat($userInfo);//更新保存信息
            }catch (\Exception $e){
                Log::error($e->getMessage());
            }
        }

        if ($this->has_get_new_coupon == 0){
            $has_get = DB::table('t_user_coupons')->where('origin','=','new_user_coupon')
                ->where('get_user_id','=',$this->id)
                ->whereNull('deleted_at')->count()>0;
            if ($has_get) {
                $this->has_get_new_coupon = 1;
                $this->save();
            }
        }

        //创建邀请码
        if (!$this->invite_code) {
            $this->createInviteCode();
        }


        if($newUser) {
            $from = $request->input('from');
            $origin = ($from === "qrcode")?true:false;
            $d = ['userId'=>$this->id,'origin'=>$origin];
            Helpers::log('userId '.$this->id.' from ' . $from.' origin'.$origin,'debug');
            DB::table('sys_new_user_records')->insert([
                'user_id'=>$this->id,
                'type' => 0,
                'origin'=> $origin?1:0,
                'created_at'=>date('Y-m-d H:i:s')
            ]);
        }

    }

    //创建邀请码
    public function createInviteCode()
    {
        $this->invite_code = strtoupper(base_convert($this->id + 100000000,10,36));
        return $this->save();
    }

    public function getCanGetDayCouponAttribute()
    {
        $c = DB::table('t_user_coupons')->where('get_user_id','=',$this->id)
            ->whereRaw('origin="new_user_coupon" or origin="day_user_coupon"')
            ->where('created_at','>=',date('Y-m-d'))
            ->count() == 0;
    }
}
